import baseURL from './baseURL.js'

const request = (option) => {
  // token 缓存
  const token = uni.getStorageSync('token')
  
	return new Promise((resolve, reject) => {
    // loading 加载
    uni.showLoading({
    	title: '加载中...',
			mask: true,
    })
		uni.request({
			url: baseURL + option.url,
			method: option.method,
			data: option.data || {},
			header: { //  按需添加
				// 'Content-Type': 'application/x-www-form-urlencoded',
				"Authorization": "Bearer " + token,
			},
			success: (res) => {
				if(res.data.code == 200) {
          
				} else {
					setTimeout(()=> {
						uni.showToast({
							title: res.data.msg,
							icon: 'none',
							duration: 2500,
						})
					}, 0)
					setTimeout(() => {
						if(res.data.msg == '登录状态已过期' && res.data.code == 401){
							uni.reLaunch({
								url:'../../pages/login/index'
							})
						}
					}, 2000)
					console.log('---request---', res)
				}
        resolve(res.data)
			},
			fail: (error) => {
				setTimeout(()=> {
					uni.showToast({
						title: '请求失败',
						icon: 'error',
						duration: 2000
					})
				}, 0)
				reject(error)
			},
			// 成功或失败都执行
			complete: () => {
        // 停止loading
        uni.hideLoading()
			}
		})
	})
}

export default request